package com.example.news.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.news.MainActivity;
import com.example.news.R;
import com.example.news.helper.MediaPlayerDemo;
import com.example.news.helper.Mp3helper;
import com.example.news.helper.Ttshelper;
import com.example.news.helper.UserManage;
import com.example.news.helper.gethttp;
import com.tencent.cloud.libqcloudtts.MediaPlayer.QCloudPlayerCallback;
import com.tencent.cloud.libqcloudtts.MediaPlayer.QPlayerError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class LoginActivity extends AppCompatActivity implements  android.view.GestureDetector.OnGestureListener {
    public Context context=this;
    public String ip;
    public Mp3helper mp3helper=null;
    Handler loginhandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case 1 : {
                    try {
                        JSONObject pbj=new JSONObject(msg.obj.toString());
                        if(pbj.getString("loginresult").equals("登录成功")){
                            toast(pbj.getString("User"));
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                case 2 :break;
            }
        }
    };
    Handler getidhandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case 1 : {

                    String id=msg.obj.toString();
                    UserManage.getInstance().saveUserInfo(LoginActivity.this, id, id,"0",-1);
                    String url = "http://" + ip + ":8080/user/sign?userId=" + id + "&userPasswd=" + id + "&userName=" + id+ "&userType=2";
                    gethttp ghttp = new gethttp(url, signhandler);
                    ghttp.start();
                    Toast.makeText(LoginActivity.this,id,Toast.LENGTH_SHORT).show();
                }
                case 2 :break;
            }
        }
    };
    Handler signhandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case 1 : {
                    try {
                        JSONObject pbj=new JSONObject(msg.obj.toString());
                        if(pbj.getString("loginresult").equals("注册成功")){
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                case 2 :break;
            }
        }
    };
    //定义手势检测器实例
    GestureDetector detector;
    public Ttshelper tshelper=new Ttshelper();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mp3helper=new Mp3helper(LoginActivity.this,R.raw.login1);
        checknetwork();
        ip=this.getString(R.string.ip);
//        UserManage.getInstance().deleteuser(LoginActivity.this);
        if(UserManage.getInstance().hasUserInfo(LoginActivity.this)){
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        else   mp3helper.play(false);
        detector = new GestureDetector(this,this);
        Button login=findViewById(R.id.btn_login);
        EditText userid=findViewById(R.id.userid);
        EditText userpasswd=findViewById(R.id.passwd);
        TextView sign=findViewById(R.id.btn_sign);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id=userid.getText().toString();
                String passwd=userpasswd.getText().toString();
                MediaPlayerDemo demo=new MediaPlayerDemo(new QCloudPlayerCallback() {
                    @Override
                    public void onTTSPlayStart() {

                    }

                    @Override
                    public void onTTSPlayWait() {

                    }

                    @Override
                    public void onTTSPlayResume() {

                    }

                    @Override
                    public void onTTSPlayPause() {

                    }

                    @Override
                    public void onTTSPlayNext(String s, String s1) {

                    }

                    @Override
                    public void onTTSPlayStop() {

                    }

                    @Override
                    public void onTTSPlayError(QPlayerError qPlayerError) {

                    }

                    @Override
                    public void onTTSPlayProgress(String s, int i) {

                    }
                });
                UserManage.getInstance().saveUserInfo(LoginActivity.this, id, passwd,"0",-1);
                String url="http://"+ip+":8080/user/login?userId="+id+"&userPasswd="+passwd;
                gethttp ghttp=new gethttp(url,loginhandler);
                ghttp.start();
                try {
                    ghttp.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SignDialog dialog=new SignDialog(context,R.layout.dialog_sign,ip,signhandler);
                dialog.show();
            }
        });
    }
    public void toast(String s)
    {
        Toast.makeText(LoginActivity.this,s,Toast.LENGTH_SHORT).show();
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        detector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        float minMove = 120;         //定义最小滑动距离
        float minVelocity = 0;      //定义最小滑动速度
        float beginX = e1.getX();
        float endX = e2.getX();
        float beginY = e1.getY();
        float endY = e2.getY();

        if(beginX-endX>minMove&&Math.abs(velocityX)>minVelocity){   //左滑
            Toast.makeText(this,"左滑",Toast.LENGTH_SHORT).show();  //此处可以更改为当前动作下你想要做的事情
        }else if(endX-beginX>minMove&&Math.abs(velocityX)>minVelocity){   //右滑
            Toast.makeText(this,"右滑",Toast.LENGTH_SHORT).show();  //此处可以更改为当前动作下你想要做的事情
        }else if(beginY-endY>minMove&&Math.abs(velocityY)>minVelocity){   //上滑
            mp3helper.stop();
            String url="http://"+ip+":8080/user/getrandomid";
            gethttp ghttp=new gethttp(url,getidhandler);
            ghttp.start();
            Toast.makeText(this,"上滑",Toast.LENGTH_SHORT).show();  //此处可以更改为当前动作下你想要做的事情
        }else if(endY-beginY>minMove&&Math.abs(velocityY)>minVelocity) {   //下滑
            Toast.makeText(this, "下滑", Toast.LENGTH_SHORT).show();  //此处可以更改为当前动作下你想要做的事情
        }
        return true;
    }
    /**
     * 判断当前是否有网络连接,但是如果该连接的网络无法上网，也会返回true
     * @param mContext
     * @return
     */
    public static boolean isNetConnection(Context mContext) {
        if (mContext!=null){
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) mContext.
                            getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            boolean connected = networkInfo.isConnected();
            if (networkInfo!=null&&connected){
                if (networkInfo.getState()== NetworkInfo.State.CONNECTED){
                    return true;
                }else{
                    return false;
                }
            }
        }
        return false;
    }
    public void checknetwork() {
        if (!isNetConnection(this)) {
            tshelper.play(this, "当前无网络，请连接网络", 0);
        }
        if (ActivityCompat.checkSelfPermission(this, "android.permission.INTERNET") == 1 || ActivityCompat.checkSelfPermission(this, "android.permission.ACCESS_NETWORK_STATE") == 1) {
            tshelper.play(this, "网络权限未开启，请让您身边的朋友替您开启", 0);
        }
    }
}